package com.soyea.controller;

import com.soyea.model.SysUser;
import com.soyea.service.SysUserService;
import com.soyea.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录功能
 * Created by skh on 2018/1/4
 */
@Controller
@Slf4j
public class UserController {

	@Autowired
	private SysUserService sysUserService;

	/**
	 * 用户退出
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/logout.page")
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.getSession().invalidate();
		String path = "signin.jsp";
		response.sendRedirect(path);
	}

	/**
	 * 用户登录
	 * 账号:admin@qq.com
	 * 密码:12345678
	 *
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/login.page")
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		//根据username查找用户,username可以是telephone 或者 email
		SysUser sysUser = sysUserService.findByKeyword(username);
		log.debug("username={}的用户信息:{}", sysUser);
		String errorMsg = "";
		//之前请求的url,登陆后重新执行这个请求
		String ret = request.getParameter("ret");


		if (StringUtils.isBlank(username)) {
			errorMsg = "用户名不可以为空";
		} else if (StringUtils.isBlank(password)) {
			errorMsg = "密码不可以为空";
		} else if (sysUser == null) {
			errorMsg = "查询不到指定的用户";
		} else if (!sysUser.getPassword().equals(MD5Util.encrypt(password))) {
			errorMsg = "用户名或密码错误";
		} else if (sysUser.getStatus() != 1) {
			errorMsg = "用户已被冻结，请联系管理员";
		} else {
			// login success
			request.getSession().setAttribute("user", sysUser);
			log.info("用户:{}成功登录", sysUser);
			if (StringUtils.isNotBlank(ret)) {
				response.sendRedirect(ret);
				return;
			} else {
				response.sendRedirect("/admin/index.page");
				return;
			}
		}

		request.setAttribute("error", errorMsg);
		request.setAttribute("username", username);
		if (StringUtils.isNotBlank(ret)) {
			request.setAttribute("ret", ret);
		}

		//跳转到登录页面
		String path = "signin.jsp";
		request.getRequestDispatcher(path).forward(request, response);

	}
}
